package com.prj.ufdm.cloud.ms.order.api;

import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.prj.ufdm.cloud.ms.order.enums.ServiceNameConsts;

@RestController
@RequestMapping("/api/order")
public class OrderApi {

	@Autowired
	RestTemplate restTemplate;
	
	@RequestMapping("/test")
	@ResponseBody
	public String doGetTest() {
		String returnData = "这是由 MS-ORDER 提供的服务";
		return returnData;
	}
	
	@RequestMapping("/createorder")
	@ResponseBody
	public String doCreateOrder() throws Exception {
		
		// 查询库存
		String search_inventory_url = "http://"+ServiceNameConsts.SERVICE_MS_WAREHOUSE+"/api/warehouse/inventory/list";
		String search_inventory_result = restTemplate.getForObject(search_inventory_url, String.class);
		System.out.println("\n 库存信息："+search_inventory_result);
		
		// 创建订单
		String create_order_url = "http://"+ServiceNameConsts.SERVICE_MS_ORDER+"/api/order/create/add";
		
		HttpMethod method = HttpMethod.POST;
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		
		MultiValueMap<String, String> orderParam = new LinkedMultiValueMap<String, String>();
		orderParam.add("orderNo", String.valueOf(new Random().nextInt(100000)));
		orderParam.add("productNo", "DZ_SJ_HW_001");
		orderParam.add("userName", "张三");
		orderParam.add("address", "杭州");
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(orderParam, headers);
        ResponseEntity<String> res = restTemplate.exchange(create_order_url, method, requestEntity, String.class);
		System.out.println("\n 创建订单结果："+res.getBody());
		return res.toString();
	}
	
}
